﻿using FB.Mvc.Controllers;
using FCDB.Entity;
using FCDB.Entity.EntityEx;
using FCDB.Repository;
using FCDB.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Wf5.Engine.Business;
using Wf5.Engine.Common;
using Wf5.Engine.Core;

namespace FCDB.Web.Controllers
{
      [FB.Membership.Annotations.AuthorizeOnly]
    public class ProcessInstanceController : BaseController
    {
        //
        // GET: /ProcessInstance/
        private IWorkflowService service = new WorkflowService();
        private WfActivityInstanceTasksRepository respository = new WfActivityInstanceTasksRepository();
        private WfTasksRepository taskRepository = new WfTasksRepository();
        private WfProcessRepository processRepository = new WfProcessRepository();
        private WfProcessInstanceRepository wfpiResp = new WfProcessInstanceRepository();
        private WfActivityInstanceRepository wfactivityinstanceRespository = new WfActivityInstanceRepository();
        public ActionResult Index()
        {
            if (Request.IsAjaxRequest())
            {
                int total = 0, take = 10, skip = 0;
                int.TryParse(Request["take"], out take);
                int.TryParse(Request["skip"], out skip);
                string dtStart = Request["dtStart"];
                string dtEnd = Request["dtEnd"];
                string kewyword = Request["keyword"];
                string UserIDs = Request["UserIDs"];
                string DeparmentID = Request["DeparmentID"];
                string ProcessGuid = Request["ProcessGUID"];
                IList<WfProcessInstanceEx> list = wfpiResp.GetAllProccessInstance(0, skip, take, out total, "", 0, dtStart
                    , dtEnd, kewyword, UserIDs, DeparmentID, ProcessGuid);
                PagerModel model = new PagerModel()
                {
                    Data = list,
                    TotalCount = total
                };
                JsonResult json = new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = model
                };
                return json;

            }
            WFWorkFlowRepository WFRespository = new WFWorkFlowRepository();
            IList<WfProcess> processList = WFRespository.GetAllProcess(new[] { Entity.Enum.EntityStatus.Normal, Entity.Enum.EntityStatus.Hidden });
            ViewBag.ProcessList = processList;
            return View(); 
            
        }


        public ActionResult DepartmentProcessInstance()
        {
            if (Request.IsAjaxRequest())
            {
                int total = 0, take = 10, skip = 0;
                int.TryParse(Request["take"], out take);
                int.TryParse(Request["skip"], out skip);
                string dtStart = Request["dtStart"];
                string dtEnd = Request["dtEnd"];
                string kewyword = Request["keyword"];
                string strUserIDs = Request["UserIDs"];
                string ProcessGuid = Request["ProcessGUID"];
                IList<Guid?> UserIDs=new List<Guid?>(); 
                if (!string.IsNullOrEmpty(strUserIDs))
                {
                    string[] userIDs = strUserIDs.Split(";".ToArray());
                    foreach (string userId in userIDs)
                    {
                        if (!string.IsNullOrEmpty(userId))
                        {
                            UserIDs.Add(new Guid(userId));
                        }
                    }
                }
                else
                {
                    UserIDs = wfpiResp.GetDepartmentUser(this.UserID); 
                }  
                IList<WfProcessInstanceEx> list = wfpiResp.GetDepartmentProcessInstance(0, skip, take, out total, "", 0, dtStart
                    , dtEnd, kewyword, UserIDs, ProcessGuid);
                PagerModel model = new PagerModel()
                {
                    Data = list,
                    TotalCount = total
                };
                JsonResult json = new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = model
                };
                return json;

            }
            WFWorkFlowRepository WFRespository = new WFWorkFlowRepository();
            IList<WfProcess> processList = WFRespository.GetAllProcess(new[] { Entity.Enum.EntityStatus.Normal, Entity.Enum.EntityStatus.Hidden });
            ViewBag.ProcessList = processList;
            return View();

        }

        /// <summary>
        /// 流程返签
        /// </summary>
        /// <returns></returns>
        public ActionResult ReverseProcess()
        {
            if (string.IsNullOrEmpty(Request["AppInstanceID"])) return Content("没有存在该表单");
            RtnMsg msg = new RtnMsg()
            {
                Status = 1
            };
            string AppInstanceID = Request["AppInstanceID"];
            string AppName = Request["AppName"];
            string ProcessGUID = Request["ProcessGUID"];
            WfProcessInstance instance = service.GetProcessInstance(int.Parse(AppInstanceID));
            WfProcess process = processRepository.GetById(instance.ProcessGUID);

            try
            {
                WfAppRunner runner = new WfAppRunner()
                {
                    AppInstanceID = long.Parse(AppInstanceID),
                    AppName = instance.AppName,
                    UserID = this.UserID,
                    UserName = this.UserName,//instance.CreatedByUserName,
                    ProcessGUID = instance.ProcessGUID
                };
                WfExecutedResult result = service.SendBackProcess(runner);
                if (result.Status == WfExecutedStatus.Successed)
                {
                    msg.Message = "流程撤销成功!";
                }
            }
            catch (Exception ex)
            {
                msg.Status = 2;
                msg.Message = "流程撤回失败,你当前没有权限撤销该单据！";

            }
            JsonResult json = new JsonResult()
         {
             JsonRequestBehavior = JsonRequestBehavior.AllowGet,
             Data = msg
         };
            return json;

        }
        /// <summary>
        /// 流程取消
        /// </summary>
        /// <returns></returns>
        public ActionResult CancelProcess()
        {
            if (string.IsNullOrEmpty(Request["AppInstanceID"])) return Content("没有存在该表单");
            string AppInstanceID = Request["AppInstanceID"];
            string AppName = Request["AppName"];
            string ProcessGUID = Request["ProcessGUID"];
            WfProcessInstance instance = service.GetProcessInstance(int.Parse(AppInstanceID));
            WfProcess process = processRepository.GetById(instance.ProcessGUID);
            WfAppRunner runner = new WfAppRunner()
            {
                AppInstanceID = long.Parse(AppInstanceID),
                AppName = instance.AppName,
                UserID = (Guid)instance.CreatedByUserID,
                UserName = instance.CreatedByUserName,
                ProcessGUID = instance.ProcessGUID
            };
            bool flag=  service.CancelProcess(runner);
            if (flag == true)
            {
                return Content("流程取消成功！");
            }
            else
            {
                return Content("流程取消失败！");
            }
        }


        /// <summary>
        /// 流程撤回
        /// </summary>
        /// <returns></returns>
        public ActionResult ProcessSendBack()
        {
            if (string.IsNullOrEmpty(Request["AppInstanceID"])) return Content("没有存在该表单");
            string AppInstanceID = Request["AppInstanceID"];
          WfProcessInstance wfProcessInstance=  service.GetProcessInstance(int.Parse(AppInstanceID));
            string AppName = Request["AppName"];
            string ProcessGUID = Request["ProcessGUID"];
            RtnMsg msg = new RtnMsg()
            {
                Status = 1
            };
            JsonResult json = null;
            TaskQueryEntity taskQuery = new TaskQueryEntity()
                {
                    AppInstanceID = long.Parse(AppInstanceID),
                    AppName = wfProcessInstance.AppName,
                    ProcessGUID = wfProcessInstance.ProcessGUID,
                    UserID = this.UserID,
                    UserName = this.UserName,
                    PageIndex = 1,
                    PageSize = 50
                }; 
          IList<WfActivityInstanceTasksEx> taskList=  service.GetNextTask(taskQuery);
          if (taskList.Count() == 0)
          {
              msg.Status =  2;
              msg.Message = "该流程不存在可以撤回的步骤!无法撤回";
              json = new JsonResult()
              {
                  JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                  Data = msg
              };
              return json;
          }
          else
          {
             if(taskList.Count(t=>t.TaskState==2)>0)
             {
                 taskList = taskList.Where(t => t.TaskState == 2).ToList();
                 msg.Status = 2;
                 StringBuilder str = new StringBuilder();
                 str.Append("该流程已经被");
                 foreach (var item in taskList)
                 {
                  WfTasks task=   taskRepository.Get<WfTasks>(item.TaskID);
                  str.Append(task.LastUpdatedByUserName + ",");
                 }
                 str.Append("打开，无法撤回");
                 msg.Message = str.ToString();
                 json = new JsonResult()
                 {
                     JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                     Data = msg
                 };
                 return json;
             }
          }
          
            WfProcessInstance instance = service.GetProcessInstance(int.Parse(AppInstanceID));
            WfProcess process = processRepository.GetById(instance.ProcessGUID);

            try
            {
                WfAppRunner runner = new WfAppRunner()
                {
                    AppInstanceID = long.Parse(AppInstanceID),
                    AppName = instance.AppName,
                    UserID = this.UserID,
                    UserName = this.UserName,
                    ProcessGUID = instance.ProcessGUID
                };
                WfExecutedResult result = service.SendBackProcess(runner);
                if (result.Status == WfExecutedStatus.Successed)
                {
                    msg.Message = "流程撤销成功!";
                }
            }
            catch (Exception ex)
            {
                msg.Status = 2;
                msg.Message = "流程撤回失败,你当前没有权限撤销该单据！";

            }
              json = new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = msg
            };
            return json;

        }
    }
}
